﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.IO;
using System.Text;
using Excel;

namespace OrderAggregator.InputFormats.Excel
{
	/// <summary>
    /// 
	/// </summary>
    public class Excel2Format : Excel.BaseExcelFormat
	{
        public readonly static Excel2Format Instance = new Excel2Format();

        private Excel2Format()
        {
        }

		/// <summary>
		/// Parse
		/// </summary>
		/// <param name="filePath"></param>
		/// <param name="getStream"></param>
		/// <returns></returns>
		public override BaseOrder Parse(string filePath, Func<System.IO.Stream> getStream)
		{
            if (!string.Equals(System.IO.Path.GetExtension(filePath), dotXLS, StringComparison.InvariantCultureIgnoreCase))
            {
                return null;
            }
            
            DataTable table;
            try
            {
                table = ReadAsDataTable(Path.GetFullPath(filePath));
            }
            catch
            {               
                return null;
            }
            

            string number, client;
            DateTime date;
            if (!TryParseNumberAndDateAndClient(table, out number, out date, out client))
            {
                return null;
            }


			var order = new BaseOrder();
            order.Id = number;
            order.ReceiveTime = date;
            order.Client = client;

            var orderRows = GetOrderRows(table);

            foreach (var orderDataRow in orderRows)
            {
                var orderRow = new BaseOrderRow();
                orderRow.ProductCode = orderDataRow[0].ToString();
                orderRow.ProductName = orderDataRow[2].ToString();
                orderRow.UnitName = string.Empty;
                orderRow.Count = decimal.Parse(orderDataRow[5].ToString(), BaseOrderFormat.RuCulture);                

                order.OrderRows.Add(orderRow);
            }
			return order;                     
        }
       

        private bool TryParseNumberAndDateAndClient(DataTable table, out string number, out DateTime date, out string client)
        {
            number = string.Empty;            
            date = DateTime.MinValue;
            client = string.Empty;

            var header = string.Empty;                                    
            var countField = 0;

            if (table.Columns.Count < 8)
            {
                return false;
            }

            for (var i = 0; i < table.Rows.Count && countField < 3; i++)
            {
                var row = table.Rows[i];

                header = row[0] as string;
                
                var colmn2 = row[3].ToString();

                if (!string.IsNullOrEmpty(header))
                {

                    if (string.IsNullOrEmpty(number) && header.Contains("Заказ №"))
                    {
                        number = colmn2.Trim();
                        countField++;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(number) && string.IsNullOrEmpty(client) && header.Contains("Магазин, адрес:"))
                        {
                            client = colmn2.Trim();
                            countField++;
                        }
                        if (!string.IsNullOrEmpty(number) && !string.IsNullOrEmpty(client) && header.Contains("Дата поставки:"))
                        {

                            if (!string.IsNullOrEmpty(colmn2) && !DateTime.TryParse(colmn2, out date))
                            {
                                date = DateTime.FromOADate(double.Parse(colmn2));
                            }
                            countField++;
                        }
                    }
                }
            }

            if (countField < 3)
            {
                return false;
            }
          
            return true;
        }

        private static List<DataRow> GetOrderRows(DataTable table)
        {
            var rows = new List<DataRow>();

            int startRow = -1;

            for (int i = 5; i < table.Rows.Count; i++)
            {
                var row = table.Rows[i];

                var strColmn1 = row[0] as string;
                var strColmn2 = row[1] as string;

                if (string.Equals(strColmn1, "Код", StringComparison.InvariantCultureIgnoreCase) &&
                    string.Equals(strColmn2, "Штрихкод", StringComparison.InvariantCultureIgnoreCase))
                {
                    startRow = i + 1;
                    break;
                }
            }

            if (startRow < 0)
            {
                return rows;
            }

            for (int i = startRow; i < table.Rows.Count; i++)
            {
                var row = table.Rows[i];

                var strColmn1 = row[1] as string;

                if (string.IsNullOrEmpty(strColmn1))
                {
                    break;
                }

                rows.Add(row);
            }

            return rows;
        }
	}
}
